package excel

import (
	"fmt"
	"io"

	"github.com/xuri/excelize/v2"
)

type Document struct {
	file *excelize.File
}

// 写入文件流
func (doc *Document) Write(w io.Writer) error {
	return doc.file.Write(w)
}

// 写入文件
func (doc *Document) WriteTo(w io.Writer) (int64, error) {
	return doc.file.WriteTo(w)
}

// 关闭文件
func (doc *Document) Close() {
	doc.file.Close()
}

// 通过数据字典设置下拉框
// @param sheet 			数据表名称
// @param sqref				应用范围
// @param name  			字典表名称
func (doc *Document) SelectValidation(sheet *SheetStream, sqref string, name string) error {

	e := doc.file.SetDefinedName(&excelize.DefinedName{
		Name:     "DynamicGenderRange",
		RefersTo: "=OFFSET(dict_gender!$A$1,0,0,COUNTA(dict_gender!$A:$A),1)",
	})

	if e != nil {
		return e
	}

	// 创建数据验证器
	dv := excelize.NewDataValidation(true)
	dv.SetSqref("C1:C20")
	dv.SetSqrefDropList("DynamicGenderRange")

	// 设置下拉
	// dv.SetSqrefDropList(name + "!$A1:$A1048576")
	// dv.SetSqrefDropList("dict_gender!$A1:$A100")
	// dv.Sqref = "=OFFSET(Sheet1!$C$1,0,0,COUNTA(Sheet1!$C:$C),1)"
	// dv.Sqref = "C1:C20"
	// dv.Sqref = sqref
	// 设置字典(使用流式写入(NewStreamWriter)，数据验证需要在流式写入前添加)
	if e := doc.file.AddDataValidation("Sheet1", dv); e != nil {
		fmt.Println(e)
	}

	return nil
}
